<template>
  <div class="student-container">
    <div class="table-operations">
      <a-space>
        <a-input-search
          v-model:value="searchText"
          placeholder="搜索学生"
          style="width: 200px"
          @search="onSearch"
        />
        <a-select
          v-model:value="filterClassId"
          placeholder="选择班级"
          style="width: 200px"
          allowClear
          @change="handleFilterChange"
          :loading="classesLoading"
        >
          <a-select-option v-for="item in classes" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
        <a-button type="primary" @click="showModal()">
          <template #icon><plus-outlined /></template>
          添加学生
        </a-button>
      </a-space>
    </div>

    <a-table :columns="columns" :data-source="filteredData" :loading="loading" row-key="id">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'className'">
          {{ getClassName(record.classesId) }}
        </template>
        <template v-else-if="column.key === 'sex'">
          <a-tag :color="record.sex === '男' ? 'blue' : 'pink'">
            {{ record.sex }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a @click="showModal(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这个学生吗？"
              @confirm="handleDelete(record.id)"
            >
              <a>删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <a-modal
      v-model:visible="modalVisible"
      :title="currentRecord ? '编辑学生' : '添加学生'"
      @ok="handleOk"
      width="700px"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="姓名" name="name">
          <a-input v-model:value="formState.name" />
        </a-form-item>
        <a-form-item label="年龄" name="age">
          <a-input-number v-model:value="formState.age" :min="1" :max="100" style="width: 100%" />
        </a-form-item>
        <a-form-item label="性别" name="sex">
          <a-radio-group v-model:value="formState.sex">
            <a-radio value="男">男</a-radio>
            <a-radio value="女">女</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="班级" name="classesId">
          <a-select v-model:value="formState.classesId" :loading="classesLoading">
            <a-select-option v-for="item in classes" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="地址" name="address">
          <a-input v-model:value="formState.address" />
        </a-form-item>
        <a-form-item label="电话" name="phone">
          <a-input v-model:value="formState.phone" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" />
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-textarea v-model:value="formState.remark" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import request from '../../utils/request'

const API_URL = '/students'
const CLASSES_API_URL = '/classes'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: '60px'
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: '100px'
  },
  {
    title: '年龄',
    dataIndex: 'age',
    key: 'age',
    width: '80px'
  },
  {
    title: '性别',
    dataIndex: 'sex',
    key: 'sex',
    width: '80px'
  },
  {
    title: '班级',
    key: 'className',
    width: '120px'
  },
  {
    title: '电话',
    dataIndex: 'phone',
    key: 'phone',
    width: '120px'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
  },
  {
    title: '地址',
    dataIndex: 'address',
    key: 'address',
  },
  {
    title: '操作',
    key: 'action',
    width: '120px',
    fixed: 'right'
  },
]

const data = ref([])
const classes = ref([])
const loading = ref(false)
const classesLoading = ref(false)
const searchText = ref('')
const filterClassId = ref(undefined)
const modalVisible = ref(false)
const currentRecord = ref(null)
const formRef = ref()

const formState = reactive({
  name: '',
  age: 18,
  sex: '男',
  address: '',
  phone: '',
  email: '',
  remark: '',
  classesId: undefined
})

const rules = {
  name: [{ required: true, message: '请输入学生姓名!' }],
  age: [{ required: true, message: '请输入年龄!' }],
  sex: [{ required: true, message: '请选择性别!' }],
  classesId: [{ required: true, message: '请选择班级!' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码!', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址!', trigger: 'blur' }],
}

// 根据搜索文本和班级过滤数据
const filteredData = computed(() => {
  let result = [...data.value]
  
  // 按班级筛选
  if (filterClassId.value) {
    result = result.filter(item => item.classesId === filterClassId.value)
  }
  
  // 按搜索文本筛选
  if (searchText.value) {
    const keyword = searchText.value.toLowerCase()
    result = result.filter(item => 
      item.name.toLowerCase().includes(keyword) ||
      (item.phone && item.phone.includes(keyword)) ||
      (item.email && item.email.toLowerCase().includes(keyword)) ||
      (item.address && item.address.toLowerCase().includes(keyword))
    )
  }
  
  return result
})

// 获取班级名称
const getClassName = (classId) => {
  const classItem = classes.value.find(item => item.id === classId)
  return classItem ? classItem.name : '未分配班级'
}

// 搜索处理
const onSearch = (value) => {
  searchText.value = value
}

// 处理筛选条件变化
const handleFilterChange = () => {
  // 筛选条件已经通过计算属性自动应用
}

// 显示模态框
const showModal = (record = null) => {
  currentRecord.value = record
  if (record) {
    Object.assign(formState, record)
  } else {
    Object.assign(formState, {
      name: '',
      age: 18,
      sex: '男',
      address: '',
      phone: '',
      email: '',
      remark: '',
      classesId: undefined
    })
  }
  modalVisible.value = true
}

// 处理表单提交
const handleOk = () => {
  formRef.value.validate().then(() => {
    if (currentRecord.value) {
      // 更新学生
      updateStudent(currentRecord.value.id, formState)
    } else {
      // 创建学生
      createStudent(formState)
    }
  }).catch(error => {
    console.error('Validation failed:', error)
  })
}

// 处理删除
const handleDelete = (id) => {
  deleteStudent(id)
}

// 获取所有学生
const fetchStudents = async () => {
  loading.value = true
  try {
    const result = await request.get(API_URL)
    data.value = result
  } catch (error) {
    console.error('Error fetching students:', error)
    message.error('获取学生列表失败')
  } finally {
    loading.value = false
  }
}

// 获取所有班级
const fetchClasses = async () => {
  classesLoading.value = true
  try {
    const result = await request.get(CLASSES_API_URL)
    classes.value = result
  } catch (error) {
    console.error('Error fetching classes:', error)
    message.error('获取班级列表失败')
  } finally {
    classesLoading.value = false
  }
}

// 创建学生
const createStudent = async (studentData) => {
  loading.value = true
  try {
    const result = await request.post(API_URL, studentData)
    data.value.push(result)
    message.success('学生添加成功')
    modalVisible.value = false
  } catch (error) {
    console.error('Error creating student:', error)
    message.error('学生添加失败')
  } finally {
    loading.value = false
  }
}

// 更新学生
const updateStudent = async (id, studentData) => {
  loading.value = true
  try {
    const result = await request.put(`${API_URL}/${id}`, studentData)
    const index = data.value.findIndex(item => item.id === id)
    if (index !== -1) {
      data.value[index] = result
    }
    message.success('学生更新成功')
    modalVisible.value = false
  } catch (error) {
    console.error('Error updating student:', error)
    message.error('学生更新失败')
  } finally {
    loading.value = false
  }
}

// 删除学生
const deleteStudent = async (id) => {
  loading.value = true
  try {
    await request.delete(`${API_URL}/${id}`)
    data.value = data.value.filter(item => item.id !== id)
    message.success('学生删除成功')
  } catch (error) {
    console.error('Error deleting student:', error)
    message.error('学生删除失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchStudents()
  fetchClasses()
})
</script>

<style scoped>
.student-container {
  padding: 24px;
}

.table-operations {
  margin-bottom: 16px;
}
</style>